package com.fwtai.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fwtai.bean.AccessToken;
import com.fwtai.bean.RefreshToken;
import com.fwtai.dao.ApiDao;
import com.fwtai.tool.ToolClient;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApiService{

  private final ApiDao apiDao;

  public ApiService(final ApiDao apiDao){
    this.apiDao = apiDao;
  }

  public String requestGet(final String url) throws IOException{
    final URL uri = new URL(url);
    final HttpURLConnection http = (HttpURLConnection) uri.openConnection();
    http.setRequestMethod("GET");
    return reader(http);
  }

  private String reader(final HttpURLConnection conn) throws IOException{
    final BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    final StringBuilder sb = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
      sb.append(inputLine);
    }
    in.close();
    return sb.toString();
  }

  public String requestPost(final String url,final String data) throws IOException{
    final URL uri = new URL(url);
    final HttpURLConnection http = (HttpURLConnection) uri.openConnection();
    http.setRequestMethod("POST");
    http.setRequestProperty("User-Agent", "pan.baidu.com");
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setDoOutput(true);
    final OutputStreamWriter writer = new OutputStreamWriter(http.getOutputStream());
    writer.write(data);
    writer.flush();
    writer.close();
    http.getOutputStream().close();
    return reader(http);
  }

  //通过授权码获取 Access Token
  public int getAccessToken(final String code){
    final int kid = 39630237;
    final AccessToken accessToken = apiDao.queryAccessToken(kid);
    try {
      //必须是同一个 AppKey 获取的code去换拿获取token才有效 https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=j61RTI6qcDDpDAyzQjOlLQV7YPGWqTir&redirect_uri=oob&scope=basic,netdisk&device_id=39630237
      final String url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code="+code+"&client_id="+accessToken.getClientId()+"&client_secret="+accessToken.getClientSecret()+"&redirect_uri=oob";
      final String result = requestGet(url);
      final HashMap<String,String> map = new ObjectMapper().readValue(result,new TypeReference<>(){});
      return update(kid,map.get("access_token"),map.get("refresh_token"));//百度云的应用id
    } catch (final Exception e){
      return 0;
    }
  }

  private int update(final int kid,final String access_token,final String refresh_token){
    return apiDao.update(kid,access_token,refresh_token);
  }

  //刷新 Access Token
  public int refreshToken(final int kid){
    try {
      final RefreshToken refreshToken = apiDao.queryRefreshToken(kid);
      final String url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=refresh_token&refresh_token="+refreshToken.getRefreshToken()+"&client_id="+refreshToken.getClientId()+"&client_secret="+refreshToken.getClientSecret();
      final String result = requestGet(url);
      final HashMap<String,String> hashMap = new ObjectMapper().readValue(result,new TypeReference<>(){});
      return update(kid,hashMap.get("access_token"),hashMap.get("refresh_token"));
    } catch (final Exception e) {
      return 0;
    }
  }

  //重命名
  private void rename(){
    try {
      final String url = "http://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=12.a6b7dbd428f731035f771b8d15063f61.86400.1292922000-2346678-124328&opera=rename";
      final String data = "async=1&filelist=[{\"path\":\"/apps/test\",\"newname\":\"/test1\"}]&ondup=fail";
      final String result = requestPost(url,data);
      System.out.println(result);
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  //删除文件(一次仅能删除一个文件),ok
  public static void deleteFile(final String access_token,final String filePath){
    try {
      final URL url = new URL("http://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&opera=delete&access_token="+access_token);
      final HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
      httpConn.setRequestMethod("POST");
      httpConn.setRequestProperty("User-Agent", "pan.baidu.com");
      httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      httpConn.setDoOutput(true);
      final OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
      //writer.write("async=1&ondup=fail&filelist=[{\"path\":\"/apps/bakups/wxb/bdrz.jpg\"}]");
      writer.write("async=1&ondup=fail&filelist=[{\"path\":\""+filePath+"\"}]");
      writer.flush();
      writer.close();
      httpConn.getOutputStream().close();

      final int responseCode = httpConn.getResponseCode();
      System.out.println("Response Code : " + responseCode);
      final BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
      String inputLine;
      final StringBuffer response = new StringBuffer();
      while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
      }
      in.close();
      System.out.println(response.toString());
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public String getClientId(){
    return apiDao.getClientId(39630237);
  }

  public String getInfo(final Integer kid){
    try {
      final Map<String,Object> info = apiDao.getInfo(kid);
      if(info == null){
        return ToolClient.createJson(201,"暂无数据",null);
      }
      return ToolClient.createJson(200,"操作成功",info);
    } catch (final Exception ignored) {
      return ToolClient.createJson(205,"服务出现错误",null);
    }
  }
}